package org.example.springboot.service;

import org.example.springboot.entity.AIConversation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class ConversationStorage {
    private final RedisTemplate<String, Object> redisTemplate;

    public ConversationStorage(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 保存会话
    public void saveConversation(AIConversation conversation) {
        // 存储会话详情
        String conversationKey = "conversation:" + conversation.getUserId() + ":" + conversation.getConversationId();
        redisTemplate.opsForValue().set(conversationKey, conversation, 7, TimeUnit.DAYS);

        // 将会话ID添加到用户的会话列表中
        String userConversationsKey = "user:" + conversation.getUserId() + ":conversations";
        redisTemplate.opsForSet().add(userConversationsKey, conversation.getConversationId());
        redisTemplate.expire(userConversationsKey, 7, TimeUnit.DAYS);
    }

    // 获取特定用户的会话
    public AIConversation getConversation(Long userId, String conversationId) {
        String key = "conversation:" + userId + ":" + conversationId;
        return (AIConversation) redisTemplate.opsForValue().get(key);
    }

    // 获取用户的所有会话列表（只包含基本信息）
    public List<AIConversation> getUserConversations(Long userId) {
        String userConversationsKey = "user:" + userId + ":conversations";
        Set<Object> conversationIds = redisTemplate.opsForSet().members(userConversationsKey);

        if (conversationIds == null || conversationIds.isEmpty()) {
            return Collections.emptyList();
        }

        List<AIConversation> conversations = new ArrayList<>();
        for (Object conversationIdObj : conversationIds) {
            String conversationId = (String) conversationIdObj;
            String conversationKey = "conversation:" + userId + ":" + conversationId;
            AIConversation conversation = (AIConversation) redisTemplate.opsForValue().get(conversationKey);

            if (conversation != null) {
                // 创建一个简化版本，不包含完整的消息历史
                AIConversation simplified = new AIConversation();
                simplified.setConversationId(conversation.getConversationId());
                simplified.setTitle(conversation.getTitle());
                simplified.setCreateTime(conversation.getCreateTime());
                simplified.setUserId(conversation.getUserId());

                conversations.add(simplified);
            }
        }

        // 按创建时间倒序排序
        conversations.sort((c1, c2) -> Long.compare(c2.getCreateTime(), c1.getCreateTime()));
        return conversations;
    }

    // 删除会话
    public boolean deleteConversation(Long userId, String conversationId) {
        // 从用户会话列表中移除
        String userConversationsKey = "user:" + userId + ":conversations";
        redisTemplate.opsForSet().remove(userConversationsKey, conversationId);

        // 删除会话详情
        String conversationKey = "conversation:" + userId + ":" + conversationId;
        return redisTemplate.delete(conversationKey);
    }
}